<?php
declare (strict_types = 1);

namespace app\admin\controller;

use app\common\controller\AdminController;
use think\facade\Db;
use app\common\utils\JsonResponse;
use think\facade\Request;

class AudioRecords extends AdminController
{
    /**
     * 获取音频记录列表
     */
    public function list()
    {
        try {
            $page = Request::param('page/d', 1);
            $limit = Request::param('limit/d', 10);
            $userId = Request::param('user_id/d', 0);
            $startTime = Request::param('start_time', '');
            $endTime = Request::param('end_time', '');

            $query = Db::name('audio_records')
                ->alias('a')
                ->join('fa_user u', 'a.user_id = u.id', 'LEFT')
                ->field([
                    'a.id',
                    'a.user_id',
                    'a.audio_text',
                    'a.created_at',
                    'a.updated_at',
                    'u.username',
                    'u.avatar',
                    // 不返回 audio_base64，数据量太大
                ]);

            // 按用户ID筛选
            if ($userId > 0) {
                $query->where('a.user_id', $userId);
            }

            // 按时间范围筛选
            if ($startTime && $endTime) {
                $query->whereBetweenTime('a.created_at', $startTime, $endTime);
            }

            $total = $query->count();
            $list = $query->order('a.created_at', 'desc')
                ->page($page, $limit)
                ->select()
                ->each(function($item) {
                    // 处理音频文本，如果太长则截取
                    $item['audio_text'] = mb_strlen($item['audio_text']) > 100 
                        ? mb_substr($item['audio_text'], 0, 100) . '...' 
                        : $item['audio_text'];
                    // 处理用户头像
                    if ($item['avatar'] && strpos($item['avatar'], 'http') === false) {
                        $item['avatar'] = env('OSS_URL') . $item['avatar'];
                    }
                    return $item;
                });

            return JsonResponse::success([
                'total' => $total,
                'list' => $list,
                'page' => $page,
                'limit' => $limit
            ]);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 获取音频记录详情
     */
    public function detail()
    {
        try {
            $id = Request::param('id/d', 0);
            
            if ($id <= 0) {
                return JsonResponse::error('ID无效');
            }

            $info = Db::name('audio_records')
                ->alias('a')
                ->join('fa_user u', 'a.user_id = u.id', 'LEFT')
                ->field([
                    'a.id',
                    'a.user_id',
                    'a.audio_base64',
                    'a.audio_text',
                    'a.created_at',
                    'a.updated_at',
                    'u.username',
                    'u.avatar',
                ])
                ->where('a.id', $id)
                ->find();

            if (!$info) {
                return JsonResponse::error('记录不存在');
            }
            // 处理用户头像
            if ($info['avatar'] && strpos($info['avatar'], 'http') === false) {
                $info['avatar'] = env('OSS_DOMAIN') . $info['avatar'];
            }

            return JsonResponse::success($info);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 删除音频记录
     */
    public function delete()
    {
        try {
            $id = Request::param('id/d', 0);
            
            if ($id <= 0) {
                return JsonResponse::error('ID无效');
            }

            $result = Db::name('audio_records')
                ->where('id', $id)
                ->delete();

            return $result !== false 
                ? JsonResponse::success([], '删除成功') 
                : JsonResponse::error('删除失败');
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 批量删除音频记录
     */
    public function batchDelete()
    {
        try {
            $ids = Request::param('ids/a', []);
            
            if (empty($ids)) {
                return JsonResponse::error('请选择要删除的记录');
            }

            $result = Db::name('audio_records')
                ->whereIn('id', $ids)
                ->delete();

            return $result !== false 
                ? JsonResponse::success([], '批量删除成功') 
                : JsonResponse::error('批量删除失败');
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }

    /**
     * 导出音频文本
     */
    public function export()
    {
        try {
            $ids = Request::param('ids/a', []);
            
            $query = Db::name('audio_records')
                ->alias('a')
                ->join('fa_user u', 'a.user_id = u.id', 'LEFT')
                ->field([
                    'a.id',
                    'u.username',
                    'u.nickname',
                    'a.audio_text',
                    'a.created_at'
                ]);

            if (!empty($ids)) {
                $query->whereIn('a.id', $ids);
            }

            $list = $query->order('a.created_at', 'desc')->select();

            $data = [];
            foreach ($list as $item) {
                $data[] = [
                    'ID' => $item['id'],
                    '用户名' => $item['username'],
                    '昵称' => $item['nickname'],
                    '音频文本' => $item['audio_text'],
                    '创建时间' => $item['created_at']
                ];
            }

            return JsonResponse::success([
                'list' => $data,
                'filename' => '音频文本导出_' . date('YmdHis') . '.csv'
            ]);
        } catch (\Exception $e) {
            return JsonResponse::error($e->getMessage());
        }
    }
} 